// JavaScript Document
$(document).ready(function(e) {
    $('.btn-move').on('click', function(){
		$(this).moveItem();
		return false;
	});
});
$.fn.moveItem = function(){
		var selector = $(this);
		var table = selector.parents('table');
		var sizeitem = table.find('tbody tr').size() - 1;
		var index_move = selector.parents('tr').index();
		var move = selector.attr('href');
		if(sizeitem > 1){
			if((move=="up"&&index_move>0) || (move=="down"&&index_move<sizeitem-1)){
			
			var page = table.attr('page');
			var key = selector.parents('tr').attr('rel');
			
			$.ajax({
				type: "post",
				url: 'move' + ((page!=undefined)?'_'+page:''),
				dataType: "json",
				data: {key: key, move: move},
				success: function(data){
					if(data.success){
						var stt_move = selector.parents('tr').find('td.stt').text();
						if(move == "up"){					
							var index_change = selector.parents('tr').prev().index();
							var stt_change = selector.parents('tr').prev().find('td.stt').text();
							var subject = $(table.find('tbody tr').get(index_move));
							subject.find('td.stt').text(stt_change);
							var object = table.find('tbody tr').get(index_change);
							$(object).find('td.stt').text(stt_move);
							subject.insertBefore(object);
						}else{
							var index_change = selector.parents('tr').next().index();
							var stt_change = selector.parents('tr').next().find('td.stt').text();
							var subject = $(table.find('tbody tr').get(index_move));
							subject.find('td.stt').text(stt_change);
							var object = table.find('tbody tr').get(index_change);
							$(object).find('td.stt').text(stt_move);
							subject.insertAfter(object);
						}
						if($('body div:last-child').hasClass('tooltip')){
							$('body div.tooltip:last-child').remove();
						}	
						//location.reload();
					}
				}	
			});
			}
		}
}